/*
 * IFileTest.cpp
 *
 *  Created on: 1.4.2011
 *      Author: Tomas Srna
 */

#include "IFileTest.h"

IFileTest::IFileTest(IFile& iface, std::ostream& log)
	: interface(iface), logger(log) { all = succ = 0;}

bool IFileTest::run() {
	logger << "Testing interface: "
			<< interface.type() << std::endl;

	prepare();

	testOpen();
	testRead();
	testWrite();

	logger << "-- " << succ << " of " << all
			<< " tests succeeded." << std::endl;

	if(succ < all)
		return false;
	return true;
}

bool IFileTest::prepare() {
	try {
		interface.open("test1", "w");
		interface.write("Zapis test1\n", 12);
	}
	catch (const char * e) {
		logger << " - warning: " << e << std::endl;
		return false;
	}
	return true;
}

void IFileTest::testOpen() {
	all += 2;
	logger << " - opening existing file: ";
	try{interface.open("test1", "r");++succ;logger << "[ok]" << std::endl;}
	catch (const char * e) {logger << "[fail] " << e << std::endl;}

	logger << " - opening non-existent file: ";
	try{interface.open("testX", "r"); logger << "[fail]" << std::endl;}
	catch (...) {++succ; logger << "[ok]" << std::endl;}
}

void IFileTest::testRead() {
	all += 1;

	logger << " - reading file: ";
	try{
		interface.open("test1", "r");
		char buf[12];
		interface.read(buf, 12);
		if(0 != strncmp(buf, "Zapis test1\n", 12))
			throw "Written and read strings do not match.";
		++succ;
		logger << "[ok]" << std::endl;
	}
	catch (const char * e) {logger << "[fail] " << e << std::endl;}
}

void IFileTest::testWrite() {
	all += 1;

	logger << " - writing file: ";
	try{
		interface.open("test2", "w");
		int count = interface.write("Zapis test2\n", 12);
		if(count != 12)
			throw "Number of written bytes doesn't match.";
		++succ;
		logger << "[ok]" << std::endl;
	}
	catch (const char * e) {logger << "[fail] " << e << std::endl;}
}
